import type { User, WalletPassword, PaymentRecord } from "@/types";

/**
 * 本地存储工具类
 * 用于管理用户数据的持久化存储
 */
export class LocalStorage {
  // 存储键名
  private static readonly USERS_KEY = "novel_app_users";
  private static readonly CURRENT_USER_KEY = "novel_app_current_user";
  private static readonly TOKEN_KEY = "novel_app_token";
  private static readonly WALLET_PASSWORD_KEY = "novel_app_wallet_passwords";
  private static readonly PAYMENT_RECORDS_KEY = "novel_app_payment_records";
  private static readonly REMEMBERED_EMAIL_KEY = "novel_app_remembered_email";
  private static readonly REMEMBER_LOGIN_KEY = "novel_app_remember_login";

  /**
   * 获取所有用户
   */
  static getUsers(): User[] {
    try {
      const users = localStorage.getItem(this.USERS_KEY);
      return users ? JSON.parse(users) : [];
    } catch (error) {
      console.error("读取用户数据失败:", error);
      return [];
    }
  }

  /**
   * 保存用户（新增或更新）
   */
  static saveUser(user: User): boolean {
    try {
      const users = this.getUsers();
      const existingIndex = users.findIndex((u) => u.id === user.id);

      if (existingIndex >= 0) {
        // 更新现有用户
        users[existingIndex] = user;
      } else {
        // 添加新用户
        users.push(user);
      }

      localStorage.setItem(this.USERS_KEY, JSON.stringify(users));
      return true;
    } catch (error) {
      console.error("保存用户数据失败:", error);
      return false;
    }
  }

  /**
   * 根据邮箱查找用户
   */
  static findUserByEmail(email: string): User | null {
    const users = this.getUsers();
    return users.find((user) => user.email === email) || null;
  }

  /**
   * 根据ID查找用户
   */
  static findUserById(id: string): User | null {
    const users = this.getUsers();
    return users.find((user) => user.id === id) || null;
  }

  /**
   * 检查邮箱是否已注册
   */
  static isEmailRegistered(email: string): boolean {
    return !!this.findUserByEmail(email);
  }

  /**
   * 获取当前登录用户
   */
  static getCurrentUser(): User | null {
    try {
      const user = localStorage.getItem(this.CURRENT_USER_KEY);
      return user ? JSON.parse(user) : null;
    } catch (error) {
      console.error("读取当前用户失败:", error);
      return null;
    }
  }

  /**
   * 设置当前登录用户
   */
  static setCurrentUser(user: User): void {
    try {
      localStorage.setItem(this.CURRENT_USER_KEY, JSON.stringify(user));
    } catch (error) {
      console.error("保存当前用户失败:", error);
    }
  }

  /**
   * 移除当前登录用户
   */
  static removeCurrentUser(): void {
    try {
      localStorage.removeItem(this.CURRENT_USER_KEY);
    } catch (error) {
      console.error("移除当前用户失败:", error);
    }
  }

  /**
   * 获取访问令牌（保持向后兼容）
   */
  static getToken(): string | null {
    return this.getTokenFromStorage();
  }

  /**
   * 设置访问令牌
   */
  static setToken(token: string): void {
    try {
      localStorage.setItem(this.TOKEN_KEY, token);
    } catch (error) {
      console.error("保存令牌失败:", error);
    }
  }

  /**
   * 移除访问令牌
   */
  static removeToken(): void {
    try {
      localStorage.removeItem(this.TOKEN_KEY);
    } catch (error) {
      console.error("移除令牌失败:", error);
    }
  }

  /**
   * 获取用户总数
   */
  static getUserCount(): number {
    return this.getUsers().length;
  }

  /**
   * 导出所有用户数据
   */
  static exportUsers(): string {
    try {
      const users = this.getUsers();
      const currentUser = this.getCurrentUser();
      const token = this.getToken();

      const exportData = {
        users,
        currentUser,
        token,
        exportTime: new Date().toISOString(),
        version: "1.0",
      };

      return JSON.stringify(exportData, null, 2);
    } catch (error) {
      console.error("导出用户数据失败:", error);
      return "{}";
    }
  }

  /**
   * 导入用户数据
   */
  static importUsers(jsonData: string): boolean {
    try {
      const data = JSON.parse(jsonData);

      if (!data.users || !Array.isArray(data.users)) {
        console.error("无效的导入数据格式");
        return false;
      }

      // 验证数据完整性
      for (const user of data.users) {
        if (!user.id || !user.email || !user.nickname) {
          console.error("用户数据不完整:", user);
          return false;
        }
      }

      // 导入用户数据
      localStorage.setItem(this.USERS_KEY, JSON.stringify(data.users));

      // 如果有当前用户和令牌，也一并导入
      if (data.currentUser) {
        this.setCurrentUser(data.currentUser);
      }
      if (data.token) {
        this.setToken(data.token);
      }

      return true;
    } catch (error) {
      console.error("导入用户数据失败:", error);
      return false;
    }
  }

  /**
   * 清除用户会话数据（保留注册用户）
   */
  static clearUserData(): void {
    try {
      localStorage.removeItem(this.CURRENT_USER_KEY);
      this.clearAllTokens();
      this.clearRememberedEmail();
      this.clearRememberLogin();
    } catch (error) {
      console.error("清除用户会话数据失败:", error);
    }
  }

  /**
   * 清除所有数据
   */
  static clearAllData(): void {
    try {
      localStorage.removeItem(this.USERS_KEY);
      localStorage.removeItem(this.CURRENT_USER_KEY);
      this.clearAllTokens();
      this.clearRememberedEmail();
      this.clearRememberLogin();
    } catch (error) {
      console.error("清除所有数据失败:", error);
    }
  }

  /**
   * 获取存储统计信息
   */
  static getStorageStats() {
    const users = this.getUsers();
    const currentUser = this.getCurrentUser();
    const token = this.getToken();

    return {
      totalUsers: users.length,
      hasCurrentUser: !!currentUser,
      hasToken: !!token,
      currentUserId: currentUser?.id,
      storageSize: this.getStorageSize(),
      keys: [this.USERS_KEY, this.CURRENT_USER_KEY, this.TOKEN_KEY],
    };
  }

  /**
   * 获取存储大小（近似值）
   */
  private static getStorageSize(): number {
    try {
      let totalSize = 0;
      for (const key in localStorage) {
        if (localStorage.hasOwnProperty(key)) {
          totalSize += localStorage.getItem(key)?.length || 0;
        }
      }
      return totalSize;
    } catch (error) {
      console.error("计算存储大小失败:", error);
      return 0;
    }
  }

  // 钱包密码相关方法

  /**
   * 获取用户钱包密码信息
   */
  static getWalletPassword(userId: string): WalletPassword | null {
    try {
      const passwords = localStorage.getItem(this.WALLET_PASSWORD_KEY);
      if (!passwords) return null;

      const passwordMap = JSON.parse(passwords);
      return passwordMap[userId] || null;
    } catch (error) {
      console.error("读取钱包密码失败:", error);
      return null;
    }
  }

  /**
   * 设置用户钱包密码
   */
  static setWalletPassword(
    userId: string,
    walletPassword: WalletPassword,
    password: string,
  ): boolean {
    try {
      // 获取所有密码信息
      const passwords = localStorage.getItem(this.WALLET_PASSWORD_KEY);
      const passwordMap = passwords ? JSON.parse(passwords) : {};

      // 简单加密（实际项目中应使用更安全的加密方式）
      const encryptedPassword = btoa(password + userId);

      // 保存密码信息和加密密码
      passwordMap[userId] = walletPassword;

      localStorage.setItem(this.WALLET_PASSWORD_KEY, JSON.stringify(passwordMap));
      localStorage.setItem(`novel_app_wallet_pwd_${userId}`, encryptedPassword);

      return true;
    } catch (error) {
      console.error("设置钱包密码失败:", error);
      return false;
    }
  }

  /**
   * 验证用户钱包密码
   */
  static verifyWalletPassword(userId: string, password: string): boolean {
    try {
      const encryptedPassword = localStorage.getItem(`novel_app_wallet_pwd_${userId}`);
      if (!encryptedPassword) return false;

      const expectedEncrypted = btoa(password + userId);
      return encryptedPassword === expectedEncrypted;
    } catch (error) {
      console.error("验证钱包密码失败:", error);
      return false;
    }
  }

  // 支付记录相关方法

  /**
   * 获取用户支付记录
   */
  static getPaymentRecords(userId: string): PaymentRecord[] {
    try {
      const records = localStorage.getItem(this.PAYMENT_RECORDS_KEY);
      if (!records) return [];

      const allRecords: PaymentRecord[] = JSON.parse(records);
      return allRecords.filter((record) => record.userId === userId);
    } catch (error) {
      console.error("读取支付记录失败:", error);
      return [];
    }
  }

  /**
   * 保存支付记录
   */
  static savePaymentRecord(record: PaymentRecord): boolean {
    try {
      const records = localStorage.getItem(this.PAYMENT_RECORDS_KEY);
      const allRecords: PaymentRecord[] = records ? JSON.parse(records) : [];

      allRecords.push(record);
      localStorage.setItem(this.PAYMENT_RECORDS_KEY, JSON.stringify(allRecords));

      return true;
    } catch (error) {
      console.error("保存支付记录失败:", error);
      return false;
    }
  }

  /**
   * 保存记住的邮箱
   */
  static setRememberedEmail(email: string): void {
    try {
      localStorage.setItem(this.REMEMBERED_EMAIL_KEY, email);
    } catch (error) {
      console.error("保存记住的邮箱失败:", error);
    }
  }

  /**
   * 获取记住的邮箱
   */
  static getRememberedEmail(): string | null {
    try {
      return localStorage.getItem(this.REMEMBERED_EMAIL_KEY);
    } catch (error) {
      console.error("读取记住的邮箱失败:", error);
      return null;
    }
  }

  /**
   * 清除记住的邮箱
   */
  static clearRememberedEmail(): void {
    try {
      localStorage.removeItem(this.REMEMBERED_EMAIL_KEY);
    } catch (error) {
      console.error("清除记住的邮箱失败:", error);
    }
  }

  /**
   * 设置是否记住登录状态
   */
  static setRememberLogin(remember: boolean): void {
    try {
      localStorage.setItem(this.REMEMBER_LOGIN_KEY, remember.toString());
    } catch (error) {
      console.error("保存记住登录状态失败:", error);
    }
  }

  /**
   * 获取是否记住登录状态
   */
  static getRememberLogin(): boolean {
    try {
      const remember = localStorage.getItem(this.REMEMBER_LOGIN_KEY);
      return remember === "true";
    } catch (error) {
      console.error("读取记住登录状态失败:", error);
      return false;
    }
  }

  /**
   * 清除记住登录状态
   */
  static clearRememberLogin(): void {
    try {
      localStorage.removeItem(this.REMEMBER_LOGIN_KEY);
    } catch (error) {
      console.error("清除记住登录状态失败:", error);
    }
  }

  /**
   * 根据remember状态设置token存储策略
   */
  static setTokenWithRemember(token: string, remember: boolean): void {
    try {
      if (remember) {
        // 记住登录：使用localStorage，浏览器关闭后仍然保持
        localStorage.setItem(this.TOKEN_KEY, token);
        this.setRememberLogin(true);
      } else {
        // 不记住登录：使用sessionStorage，浏览器关闭后清除
        sessionStorage.setItem(this.TOKEN_KEY, token);
        localStorage.removeItem(this.TOKEN_KEY);
        this.setRememberLogin(false);
      }
    } catch (error) {
      console.error("保存令牌失败:", error);
    }
  }

  /**
   * 获取token（优先从localStorage获取，然后从sessionStorage获取）
   */
  static getTokenFromStorage(): string | null {
    try {
      // 先尝试从localStorage获取
      let token = localStorage.getItem(this.TOKEN_KEY);
      if (token) {
        return token;
      }

      // 再尝试从sessionStorage获取
      token = sessionStorage.getItem(this.TOKEN_KEY);
      return token;
    } catch (error) {
      console.error("读取令牌失败:", error);
      return null;
    }
  }

  /**
   * 清除所有token
   */
  static clearAllTokens(): void {
    try {
      localStorage.removeItem(this.TOKEN_KEY);
      sessionStorage.removeItem(this.TOKEN_KEY);
    } catch (error) {
      console.error("清除令牌失败:", error);
    }
  }
}
